import deezer.utils
from generic.album import Album
import deezer.track
import deezer.artist

class DeezerAlbum(Album):
  def set_raw_data(self, raw_data):
    is_page = "ALB_ID" not in raw_data
    album_data = raw_data["DATA"] if is_page else raw_data
    songs_data = raw_data["SONGS"]["data"] if is_page else album_data["SONGS"]["data"]
    return self.set_values(
      album_id = album_data["ALB_ID"],
      title = album_data["ALB_TITLE"],
      picture_url = deezer.utils.ALBUM_PICTURES_URL % album_data["ALB_PICTURE"],
      artists = list(map(
        lambda a: deezer.artist.DeezerArtist.grab_or_create(
          a["ART_ID"],
          artist_id = a["ART_ID"],
          name = a["ART_NAME"],
          picture_url = deezer.utils.ARTIST_PICTURES_URL % a["ART_PICTURE"]
        ),
        album_data["ARTISTS"]
      )),
      songs = list(map(
        lambda s: deezer.track.DeezerTrack.grab_or_create(
          s["SNG_ID"],
          raw_data = s
        ),
        songs_data
      )),
      is_full = True
    )

  def set_values(
    self,
    album_id = None,
    title = None,
    picture_url = None,
    artists = None,
    songs = None,
    is_full = False, # if the album is fully loaded
    raw_data = None
  ):
    if raw_data != None:
      self.set_raw_data(raw_data)
      return
    self.album_id = album_id
    self.title = title
    self.picture_url = picture_url
    self.artists = artists
    self.songs = songs
    if self.songs != None:
      for song in self.songs:
        song.album = self
    self.is_full = is_full

  def get_full_data(self, deezer_instance):
    if not self.is_full:
      raw_data = deezer_instance.get_album_data(self.album_id)
      self.set_raw_data(raw_data)
    if self.artists != None:
      for artist in self.artists:
        if not artist.is_full:
          artist.get_full_data(deezer_instance)
    if self.songs != None:
      for song in self.songs:
        if not song.is_full:
          song.get_full_data(deezer_instance)
